package ping.common;

import java.net.InetAddress;
import java.net.UnknownHostException;

import ping.PingServer;
import ping.client.ClientSocket;
import ping.client.Client;

/**
 * 执行命令参数解析类
 */
public abstract class Command {
	public static int getPort(String[] args) {
		return args.length != 1 ? exitWithErrorArguments(PingServer.class) : Integer.parseInt(args[0]);
	}

	public static ClientSocket getClient(String[] args) throws NumberFormatException, UnknownHostException {
		if (args.length != 2) {
			exitWithErrorArguments(Client.class);
			return null;
		}
		return new ClientSocket(Integer.parseInt(args[1]), InetAddress.getByName(args[0]));
	}

	private static <T> int exitWithErrorArguments(Class<T> clazz) {
		System.err.println("Error arguments!");
		if (clazz.getSimpleName().equals("PingServer"))
			System.out.println("Usage: java -jar ping-server.jar <port>");
		else if (clazz.getSimpleName().equals("PingClient"))
			System.out.println("Usage: java -jar ping-client.jar <host> <port>");
		return -1;
	}
}
